package il.ac.tau.cvws.scrabblesidekick.client.util.communication;

import il.ac.tau.cvws.scrabblesidekick.shared.comm.response.ResponsePayload;
import il.ac.tau.cvws.scrabblesidekick.shared.constant.CommConstants;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/* Communication services. This is boilerplate code for sending HTTP requests
 * to the server, and handling the response.
 */
public class CommServices
{
	public void sendPostRequest(final String url, final String paramName,
			final Serializable payload, final CommCallback callback) throws IOException
	{
		AsyncHttpClient client = new AsyncHttpClient();
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream    oos  = new ObjectOutputStream(baos);
		
		oos.writeObject(payload);
		oos.flush();
		oos.close();
	
		ByteArrayInputStream is = new ByteArrayInputStream(baos.toByteArray());
		
		RequestParams params = new RequestParams();
		params.put(paramName, is);
		
		client.setTimeout(CommConstants.TIMEOUT);
		
		String[] allowedContentTypes = new String[] {"application/octet-stream"};
		
		client.post(url, params, new BinaryHttpResponseHandler(allowedContentTypes) 
		{
		    @Override
		    public void onSuccess(byte[] response) 
		    {
		    	ByteArrayInputStream str = new ByteArrayInputStream(response);
		    	ObjectInputStream is = null;
		    	
		    	try
		    	{
		    		is = new ObjectInputStream(str);
			    	ResponsePayload payload = (ResponsePayload)is.readObject();
			    	callback.onSuccess(payload);
		    	}
		    	catch(Exception e)
		    	{
		    		e.printStackTrace();
		    	}
		    }
		    
		    @Override
		    public void onFailure(Throwable e, byte[] response) 
		    {
		    	e.printStackTrace();
		    	
		    	callback.onFailure();
		     }
		});
	}
}
